package vboot.core.module.mon.job.main;

import vboot.core.common.api.R;
import vboot.core.common.dao.JdbcDao;
import vboot.core.common.dao.Sqler;
import vboot.core.module.mon.job.root.MonJobHandler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("mon/job/main")
public class MonJobMainApi {

    private String table = "mon_job_main";

    @GetMapping
    public R get(String id, String name) {
        Sqler sqler = new Sqler("t.id,t.name,t.reurl,t.cron,t.avtag,t.code,t.crtim,t.notes", table);
        sqler.addLike("t.name", name);
        return R.ok(jdbcDao.findPageData(sqler));
    }

    @GetMapping("one/{id}")
    public R getOne(@PathVariable String id) {
        MonJobMain main=repo.findById(id).get();
        return R.ok(main);
    }

    @PutMapping
    public R put(@RequestBody MonJobMain main) throws SchedulerException {
        MonJobMain dbJob = repo.findById(main.getId()).get();
        if(dbJob.getAvtag()){
            String[] arr= dbJob.getReurl().split("/");
            dbJob.setJgroup(arr[0]);
            dbJob.setJid(arr[1]);
            handler.stopJob(dbJob);
        }
        repo.save(main);
        if(main.getAvtag()){
            String[] arr2= main.getReurl().split("/");
            main.setJgroup(arr2[0]);
            main.setJid(arr2[1]);
            handler.startJob(main);
        }
        return R.ok();
    }


    @PostMapping("start")
    public R startJob(String ids) throws SchedulerException {
        String[] idArr = ids.split(",");
        for (int i = 0; i < idArr.length; i++) {
            MonJobMain job = repo.findById(idArr[i]).get();
            String[] arr= job.getReurl().split("/");
            job.setJgroup(arr[0]);
            job.setJid(arr[1]);
            handler.startJob(job);
        }
        return R.ok();
    }

    @PostMapping("stop")
    public R stopJob(String ids) throws SchedulerException {
        String[] idArr = ids.split(",");
        for (int i = 0; i < idArr.length; i++) {
            MonJobMain job = repo.findById(idArr[i]).get();
            String[] arr= job.getReurl().split("/");
            job.setJgroup(arr[0]);
            job.setJid(arr[1]);
            handler.stopJob(job);
        }
        return R.ok();
    }


    @PostMapping("once")
    public R startOnce(String id) throws InterruptedException, SchedulerException {
        MonJobMain main=repo.findById(id).get();
        String[] arr= main.getReurl().split("/");
        main.setJgroup(arr[0]);
        main.setJid(arr[1]);
        handler.onceJob(main);
        return R.ok();
    }


    @Autowired
    private MonJobHandler handler;

    @Autowired
    private MonJobMainRepo repo;

    @Autowired
    private JdbcDao jdbcDao;


}